package com.liu.springmvc.handler;

import com.liu.springmvc.annotation.RequestMapping;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author LIU
 * @version 1.0
 * @date 2024/1/23 14:56
 * @description 注解请求　映射器
 */
@Component
public class MyRequestMappingHandlerMapping extends AbstractHandlerMapping implements BeanPostProcessor {

    static Map<String,Object> map =  new HashMap();


    @Override
    protected Object getHandlerInternal(HttpServletRequest request) {
        return map.get(request.getRequestURI());
    }


    /**
     * 找到所有的映射器
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

        Method[] methods = bean.getClass().getDeclaredMethods();
        for (Method method : methods) {
            HandlerMethod info = createRequestMappingInfo(method, bean);
            if (info != null){
                System.out.println("AnnotationHandlerMapping " + info);
                map.put(info.getUrl(),info);
            }
        }
        return bean;
    }


    /*
        检查方法上是否包含RequestMapping
     */
    private HandlerMethod createRequestMappingInfo(Method method, Object bean){
        HandlerMethod info = null;
        if (method.isAnnotationPresent(RequestMapping.class)){
            info = new HandlerMethod();
            info.setBean(bean);
            info.setMethod(method);
            info.setUrl(method.getDeclaredAnnotation(RequestMapping.class).value());
        }
        return info;
    }
}
